package com.justindav1s.homecontrol;

import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.util.Log;

/**
 * Created by justin on 10/11/2013.
 */
public class BluetoothDiscovery {

    private final BluetoothAdapter bluetoothAdapter;
    private final Activity clientActivity;
    private final BluetoothEventListener eventListener;

    // Create a BroadcastReceiver for ACTION_FOUND
    private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
        public void onReceive(Context context, Intent intent) {

            Log.d(Constants.LOGTAG, "Received an Intent : " + intent);

            String action = intent.getAction();
            // When discovery finds a device
            if (BluetoothDevice.ACTION_FOUND.equals(action)) {
                // Get the BluetoothDevice object from the Intent
                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                Log.d(Constants.LOGTAG, "FOUND  : " + device.getName());
                eventListener.deviceDiscovered(device);
            }
            else if (BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals(action))   {
                Log.d(Constants.LOGTAG, "DISCOVERY_STARTED");
            }
            else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action))   {
                Log.d(Constants.LOGTAG, "DISCOVERY_FINISHED");
                //eventListener.deviceDiscovered(null);
            }
        }
    };

    public BluetoothDiscovery(BluetoothAdapter _bluetoothAdapter, Activity _clientActivity) {
        bluetoothAdapter = _bluetoothAdapter;
        clientActivity = _clientActivity;
        eventListener = (BluetoothEventListener)_clientActivity;

        IntentFilter filter = new IntentFilter();
        filter.addAction(BluetoothDevice.ACTION_FOUND);
        filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
        filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
        clientActivity.registerReceiver(mReceiver,filter);
    }

    public void stopDiscovery()    {
        Log.d(Constants.LOGTAG, "UnRegistering Receiver : "+mReceiver);
        clientActivity.unregisterReceiver(mReceiver); // Don't forget to unregister during onDestroy
        bluetoothAdapter.cancelDiscovery();
    }


    public void startDiscovery() {
        Log.d(Constants.LOGTAG, "Starting Discovery");
        bluetoothAdapter.startDiscovery();
    }


}
